import contextvars
from typing import TypeAlias

context: TypeAlias = contextvars.ContextVar[str | None]


class RequestContext:
    """线程本地存储请求上下文"""

    def __init__(self) -> None:
        # 请求ID
        self.request_id: context = contextvars.ContextVar("request_id", default="")
        # 请求IP
        self.request_ip: context = contextvars.ContextVar("request_ip", default="")
        # 请求METHOD
        self.request_method: context = contextvars.ContextVar(
            "request_method", default=""
        )
        # 请求PATH
        self.request_path: context = contextvars.ContextVar("request_path", default="")

    def get(self, key: str) -> str | None:
        if isinstance(value := getattr(self, key), contextvars.ContextVar):
            return value.get()
        return None

    def set(self, key: str, value: str | None):
        if isinstance(item := getattr(self, key), contextvars.ContextVar):
            item.set(value)


request_context: RequestContext = RequestContext()
